<template>
    <div class="app-container">
        <div class="head">
            <img src="@/assets/img/Layout/position.png" />
            <p class="see-block">销售退货新建</p>
        </div>
        <div class="view-container">
            <el-row class="status-title">
                <el-col class="mr20 width100">
                    <el-button
                        class="btn-success width100"
                        type="primary"
                        @click="submitForm('save')"
                    >保存</el-button>
                </el-col>
                <el-col class="mr20 width100">
                    <el-button
                        class="btn-success width100"
                        type="primary"
                        @click="submitForm('submit')"
                    >提交</el-button>
                </el-col>
                <el-col :span="10" class="status-container">
                    <div class="status-item">
                        <span class="active">草稿</span>
                        <span>待审核</span>
                        <span>已审核</span>
                        <span>拒绝</span>
                    </div>
                </el-col>
            </el-row>
            <el-form ref="form" :model="form" label-width="100px" class="mt30">
                <el-row>
                    <el-col :span="9">
                        <el-form-item label="订单编码:" prop="code">
                            <el-input v-model="form.code" placeholder="系统自动生成" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="业务日期:" prop="businessDate">
                            <el-input v-model="form.businessDate" placeholder="系统自动生成，获取当前日期时间" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="9">
                        <el-form-item label="业务模式:" prop="businessModel">
                            销售退货
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="订单类型:" prop="orderType">
                            普通
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="9">
                        <el-form-item label="客户类型:" prop="customerType">
                            <el-select v-model="form.customerType" placeholder="请选择" style="width:100%;" @change="onCustomerType">
                                <el-option label="企业客户" value="1">企业客户</el-option>
                                <el-option label="会员客户" value="2">会员客户</el-option>
                                <el-option label="内部客户" value="3">内部客户</el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="客户名称:" prop="customerName">
                            <el-select v-if="isCustomer == 1" v-model="form.customerName" filterable placeholder="请选择" style="width:100%;" @change="selectUser">
                                <el-option v-for="(item,index) of userArr" :key="index" :label="item.name" :value="item.name"></el-option>
                            </el-select>
                            <el-select v-else-if="isCustomer == 2" v-model="form.customerName" filterable placeholder="请选择" style="width:100%;" @change="selectMemberUser">
                                <el-option v-for="(item,index) of memberUser" :key="index" :label="item.nickName" :value="item.nickName"></el-option>
                            </el-select>
                            <el-select v-else-if="isCustomer == 3" v-model="form.customerName" filterable placeholder="请选择" style="width:100%;" @change="selectCustomerDept">
                                <el-option v-for="(item,index) of customerDeptList" :key="index" :label="item.orgName" :value="item.orgName"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="9">
                        <el-form-item label="是否有源单:" prop="haveOrNot">
                            <el-radio-group v-model="form.haveOrNot">
                                <el-radio label="1">是</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="是否全退:" prop="allOrNot">
                            <el-radio-group v-model="form.allOrNot" @change="onChangeIsAllOrNot">
                                <el-radio label="1">是</el-radio>
                                <el-radio label="0">否</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="9">
                        <template v-if="salesOrderList.length > 0">
                            <el-form-item label="源销售订单:" prop="salesOrderCode">
                                <el-select v-model="form.salesOrderCode" style="width:100%;" placeholder="请选择" @change="onChangeSalesOrder">
                                    <el-option
                                        v-for="item in salesOrderList"
                                        :key="item.id"
                                        :label="item.orderCode"
                                        :value="item.orderCode">
                                    </el-option>
                                </el-select>
                                <!-- <el-button type="primary" size="small" class="btn-success" icon="el-icon-search" style="position:absolute;right:0;top:0;bottom:0;width:15%;font-size:14px;" @click="onSalesOrderList"></el-button> -->
                            </el-form-item>
                        </template>
                        <template v-else>
                            <el-form-item label="源销售订单:" prop="salesOrderCode">
                                <el-input v-model="form.salesOrderCode" placeholder="暂无" disabled />
                            </el-form-item>
                        </template>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="退货原因:" prop="reasonForReturn">
                            <el-input v-model="form.reasonForReturn" placeholder="" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="9">
                        <el-form-item label="联系人:" prop="contactName">
                            <el-input v-model="form.contactName" placeholder="" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="联系电话:" prop="contactTel">
                            <el-input v-model="form.contactTel" placeholder="" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="9">
                        <el-form-item label="销售部门:" prop="businessUnit">
                            <el-select v-model="form.businessUnit" style="width:100%;" placeholder="请选择">
                                <el-option
                                    v-for="item in businessUnitList"
                                    :key="item.deptId"
                                    :label="item.deptName"
                                    :value="item.deptName">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="备注:" prop="remark">
                            <el-input v-model="form.remark" placeholder="" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-table :data="productData">
                            <el-table-column label="序号" type="index" align="center" width="50" />
                            <el-table-column :label="item.label" :prop="item.prop" :width="item.width" v-for="(item, index) in columns" :key="index" align="center">
                                <template slot-scope="scope">
                                    <template v-if="form.allOrNot == '0'">
                                        <template v-if="item.type == '1'">
                                            <el-autocomplete
                                                v-model="scope.row[item.prop]"
                                                :fetch-suggestions="searchCode"
                                                placeholder="请输入产品编码"
                                                @select="val => handleSelect(val, scope.row)"
                                            ></el-autocomplete>
                                        </template>
                                        <template v-if="item.type == '2'">
                                            <el-autocomplete
                                                v-model="scope.row[item.prop]"
                                                :fetch-suggestions="searchName"
                                                placeholder="请输入产品名称"
                                                @select="val => handleSelect(val, scope.row)"
                                            ></el-autocomplete>
                                        </template>
                                        <template v-if="item.type == 'planNum'">
                                            <el-input placeholder="请输入数量" v-model="scope.row[item.prop]" @input="(val) => inputNum(val, scope.row)" />
                                        </template>
                                        <template v-if="item.type == '3'">{{ scope.row[item.prop] }}</template>
                                    </template>
                                    <template v-else>
                                        <template v-if="item.type == 'planNum'">
                                            <el-input placeholder="请输入数量" v-model="scope.row[item.prop]" @input="(val) => inputNum(val, scope.row)" />
                                        </template>
                                        <template v-else>{{ scope.row[item.prop] }}</template>
                                    </template>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
            </el-form>
        </div>
    </div>
</template>

<script>
import { returnAdd, returnEdit, returnDetail } from "@/api/system/salesReturn/salesReturn"
import { listUser } from "@/api/system/basedata/user/user"
import { memberList } from "@/api/system/member/member"
import { orderList, deptTree, querySalesOrder } from "@/api/system/order/order"
import { queryWarehouse } from "@/api/system/warehouse/warehouse"
export default {
    name: "add",
    data() {
        return {
            id: '',
            form: {
                code: '', // 采购退货编码
                businessDate: '', // 业务日期
                businessModel: '0', // 业务模式
                orderType: '0', // 订单类型
                customerType: '1', // 客户类型 1 企业客户 2 会员
                customerId: '', // 客户id
                customerName: '', // 客户名称
                haveOrNot: '1', // 是否有源单
                allOrNot: '1', // 是否全退
                salesOrderId: '', // 源采购订单id
                salesOrderCode: '', // 源采购订单
                reasonForReturn: '', // 退货原因
                contactName: '', // 联系人
                contactTel: '', // 联系电话
                businessUnit: '', // 销售部门
                remark: '', // 备注
                salesReturnOrderDetailList: [], // 商品数据
            },
            isCustomer: 1,
            userArr: [], // 企业客户
            memberUser: [], // 会员客户
            customerDeptList: [], // 内部客户
            salesOrderList: [], // 源采购订单列表
            businessUnitList: [], // 销售部门
            searchProductList: [], // 产品列表数据
            warehouseList: [], // 仓库列表
            // 表头
            columns: [{
                prop: "productBasicCode",
                label: "产品编码",
                width: 180,
                type: '1'
            },{
                prop: "productBasicName",
                label: "产品名称",
                type: '2',
                width: 150,
            },{
                prop: "specificationCode",
                label: "SKU编码",
                width: 150,
                type: '1'
            },{
                prop: "productSpace",
                label: "规格",
                width: 120,
                type: '3'
            },{
                prop: "unit",
                label: "单位",
                width: 100,
                type: '3'
            },{
                prop: "unitPrice",
                label: "单价",
                width: 100,
                type: '3'
            },{
                prop: "picksNum",
                label: "可退数量",
                width: 100,
                type: '3'
            },{
                prop: "planNum",
                label: "申退数量",
                width: 100,
                type: 'planNum'
            },{
                prop: "warehouseName",
                label: "仓库",
                width: 120,
                type: '3'
            },{
                prop: "remark",
                label: "备注",
                type: '3'
            }],
            // 产品数据
            productData: [],
            open: false, // 源采购订单弹窗
            queryPurchaseOrderList: [], // 源采购订单弹窗列表数据
            queryPurchaseOrderId: '',
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                supplierInfoId: undefined,
                searchValue: undefined,
                approvalStatus: 1
            },
        }
    },
    created() {
        let userInfo = this.$store.state.user.users
        // 部门
        this.businessUnitList.push({
            deptId: userInfo.dept.deptId,
            deptName: userInfo.dept.deptName
        })
        this.getListUser()
    },
    methods: {
        // 获取详情信息
        getDetailData() {
            returnDetail(this.id).then(res => {
                this.form = res.data
                if(res.data.salesReturnOrderDetailList == null){
                    this.productData = []
                }else{
                    res.data.salesReturnOrderDetailList.forEach(item => {
                        if(item.planNum == 0){
                            item.planNum = ''
                        }
                    })
                    this.productData = res.data.salesReturnOrderDetailList
                }
            })
        },
        // 获取仓库列表
        getWarehouseList(){
            queryWarehouse().then(res => {
                if(res.code == 200){
                    this.warehouseList = res.data
                }
            })
        },
        // 客户类型
        onCustomerType(val){
            if(this.productData.length > 0){
                this.productData = []
            }
            this.form.customerId = ''
            this.form.customerName = ''
            if(val == '1'){
                this.getListUser()
                this.isCustomer = 1
            }else if(val == '2'){
                this.getMemberUser()
                this.isCustomer = 2
            }else{
                this.getDeptTree()
                this.isCustomer = 3
            }
        },
        // 获取企业客户
        getListUser(){
            listUser(this.addDateRange({status: 1, approvalStatus: 2})).then(res => {
                this.userArr = res.rows
            })
        },
        // 选中企业客户数据
        selectUser(e){
            let data = this.userArr.find(i => i.name == e)
            this.form.customerId = data.id
            this.productData = []
            this.form.salesOrderId = ''
            this.form.salesOrderCode = ''
            this.getSalesOrderList(e)
        },
        // 获取会员客户
        getMemberUser(){
            memberList(this.addDateRange({status: '2'})).then(res => {
                this.memberUser = res.rows
            })
        },
        // 选中会员客户数据
        selectMemberUser(e){
            let data = this.memberUser.find(i => i.nickName == e)
            this.form.customerId = data.memberInformationId
            this.productData = []
            this.form.salesOrderId = ''
            this.form.salesOrderCode = ''
            this.getSalesOrderList(e)
        },
        // 获取内部客户
        getDeptTree(){
            deptTree().then(res => {
                this.customerDeptList = res.data
            })
        },
        // 选中内部客户数据
        selectCustomerDept(e){
            let data = this.customerDeptList.find(i => i.orgName == e)
            this.form.customerId = data.id
            this.productData = []
            this.form.salesOrderId = ''
            this.form.salesOrderCode = ''
            this.getSalesOrderList(e)
        },
        // 获取销售订单列表
        getSalesOrderList(e){
            this.getWarehouseList()
            querySalesOrder({customerName: e, approveStatus: 1, customerType: this.form.customerType}).then(res => {
                this.salesOrderList = res.rows
            })
        },
        // 选择源采购订单
        onChangeSalesOrder(val){
            if(this.form.customerId == ''){
                this.$modal.msgError('客户不能为空！')
                this.form.salesOrderId = ''
                this.form.salesOrderCode = ''
            }else{
                this.getSalesOrderData(val)
            }
        },
        // 源订单数据
        getSalesOrderData(val){
            let salesOrder = this.salesOrderList.find(i => i.orderCode == val)
            this.form.salesOrderId = salesOrder.id
            let arr = []
            salesOrder.salesOrderDetailList.map(i => {
                arr.push(Object.assign(
                    {},{
                        // orderId: i.orderId,
                        productBasicId: i.productBasicId,
                        productBasicCode: i.productBasicCode,
                        productBasicName: i.productBasicName,
                        specificationId: i.productId,
                        specificationCode: i.productCode,
                        specificationName: i.productName,
                        productSpace: i.productSpace,
                        unit: i.unit,
                        unitPrice: i.unitPrice,
                        picksNum: i.returnCount,
                        planNum: i.outStore == 0 ? '' : i.outStore,
                        totalPrice: i.totalPrice,
                        taxedUnitPrice: i.taxUnitPrice,
                        taxRate: i.taxRate,
                        levy: i.taxPrice,
                        totalTax: i.totalPriceTax,
                        warehouseId: i.warehouse,
                        warehouseName: '',
                        batchNumber: i.batchNumber,
                        realNum: '',
                        remark: i.remark
                    }
                ))
            })
            arr.forEach(i => {
                let dataList = this.warehouseList.find(item => {
                    return item.warehouseId == i.warehouseId
                })
                if(dataList != undefined){
                    i.warehouseName = dataList.name
                }
            })
            if(this.form.allOrNot == '1'){
                this.productData = arr
            }else{
                this.addProduct()
                this.searchProductList = arr
            }
        },
        // 弹出销售订单列表
        onSalesOrderList(){},
        // 是否全退 1是 0否
        onChangeIsAllOrNot(){
            this.productData = []
            if(this.form.salesOrderId !== ''){
                this.getSalesOrderData(this.form.salesOrderCode)
            }
        },
        // 新建产品数据
        addProduct(){
            let data = {
                key: {
                    specificationId: ''
                }
            }
            this.columns.forEach(item =>{
                data.key[item.prop] = ''
            })
            this.productData.push(JSON.parse(JSON.stringify(data.key)))
        },
        // 产品编码搜索
        searchCode(val, cb) {
            let list = []
            this.searchProductList.map(item => {
                list.push(Object.assign(
                    {},item,{
                        value: item.specificationCode
                    }
                ))
            })
            var arr = list
            var results = val ? arr.filter(this.createFilter(val)) : arr
            cb(results)
        },
        // 产品名称搜索
        searchName(val, cb){
            let list = []
            this.searchProductList.map(item => {
                list.push(Object.assign(
                    {},item,{
                        value: item.specificationName
                    }
                ))
            })
            var arr = list
            var results = val ? arr.filter(this.createFilter(val)) : arr
            cb(results)
        },
        // 匹配
        createFilter(val) {
            return (res) => {
                return (res.value.toLowerCase().indexOf(val.toLowerCase()) === 0)
            }
        },
        // 选中产品
        handleSelect(item, row){
            // row.orderId = item.orderId
            row.productBasicId = item.productBasicId
            row.productBasicCode = item.productBasicCode
            row.productBasicName = item.productBasicName
            row.specificationId = item.specificationId // 产品id
            row.specificationCode = item.specificationCode // 产品编码
            row.specificationName = item.specificationName // 产品名称
            row.productSpace = item.productSpace // 规格
            row.unit = item.unit // 单位
            row.unitPrice = item.unitPrice // 单价
            row.picksNum = item.picksNum // 可退数量
            row.planNum = item.planNum == 0 ? '' : item.planNum // 申退数量
            row.totalPrice = item.totalPrice // 金额
            row.taxedUnitPrice = item.taxedUnitPrice // 含税单价
            row.taxRate = item.taxRate // 税率
            row.levy = item.levy // 税额
            row.totalTax = item.totalTax // 价税合计
            row.warehouseId = item.warehouseId // 仓库id
            row.warehouseName = item.warehouseName // 仓库名称
            row.batchNumber = item.batchNumber // 批次
            row.realNum = item.realNum // 实退数量
            row.remark = item.remark // 备注
            // 过滤已选择的产品
            let filterProductList = this.searchProductList.filter(item => item.specificationId !== row.specificationId)
            this.searchProductList = filterProductList
            // 插入已选择产品
            let arr = this.productData.filter(item => item.specificationCode !== '')
            if(arr && arr.length > 0){
                this.productData = arr
                if(filterProductList.length > 0){
                    this.addProduct()
                }
            }
        },
        // 数量验证
        inputNum(val, row){
            if(val == '' || val == undefined){
                this.$modal.msgError('申退数量不能为空!')
                row.planNum = ''
                row.totalTax = ''
                row.levy = ''
            }else{
                if(/^[1-9]\d*$|^0$/.test(val) == false){
                    this.$modal.msgError('申退数量必须是数字！')
                    row.planNum = ''
                    return false
                }else{
                    if(JSON.parse(val) <= 0){
                        this.$modal.msgError('申退数量必须大于0!')
                        row.planNum = ''
                    }else{
                        if(JSON.parse(val) > row.picksNum){
                            row.planNum = ''
                            row.totalTax = ''
                            row.levy = ''
                            this.$modal.msgError('申退数量不能大于可退数量!')
                        }else{
                            let str = row.taxRate.substring(0, row.taxRate.lastIndexOf('%'))
                            row.totalTax = (row.planNum * row.taxedUnitPrice).toFixed(2) // 价税合计
                            row.levy = ((row.totalTax / (1 + (Number(str) / 100))) * (Number(str) / 100)).toFixed(2) // 税额
                        }
                    }
                }
            }
        },
        // 保存/提交
        submitForm(e){
            let arr = this.productData.filter(item => item.specificationCode !== '')
            let planNum = arr.every(val => !!val.planNum)
            this.form.salesReturnOrderDetailList = arr
            // console.log(this.form)
            if(e == 'save'){
                // 保存
                if(this.id){
                    let data = this.form
                    data.id = this.id
                    this.$modal.loading("正在保存")
                    returnEdit(data).then(res=> {
                        if(res.code == 200){
                            this.getDetailData()
                            this.$modal.msgSuccess("保存成功")
                            this.$modal.closeLoading()
                        }
                    })
                }else{
                    this.$modal.loading("正在保存")
                    returnAdd(this.form).then(res => {
                        if(res.code == 200){
                            this.id = res.data.id
                            this.getDetailData()
                            this.$modal.msgSuccess("保存成功")
                            this.$modal.closeLoading()
                        }
                    })
                }
            }else{
                if(arr.length > 0){
                    if(planNum == true){
                        // 提交
                        if(this.id){
                            let data = this.form
                            data.id = this.id
                            data.approvalStatus = 1
                            this.$modal.loading("正在提交")
                            returnEdit(data).then(res=> {
                                if(res.code == 200){
                                    this.$refs.form.resetFields()
                                    this.$tab.closeOpenPage({ path: "/sales/salesReturn/list" })
                                    this.$modal.msgSuccess("新建成功")
                                    this.$modal.closeLoading()
                                }
                            })
                        }else{
                            let data = this.form
                            data.approvalStatus = 1
                            this.$modal.loading("正在提交")
                            returnAdd(data).then(res=> {
                                if(res.code == 200){
                                    this.$refs.form.resetFields()
                                    this.$tab.closeOpenPage({ path: "/sales/salesReturn/list" })
                                    this.$modal.msgSuccess("新建成功")
                                    this.$modal.closeLoading()
                                }
                            })
                        }
                    }else{
                        this.$modal.msgError('申退数量不能为空！')
                    }
                }else{
                    this.$modal.msgError('请选择产品！')
                }
            }
        }
    }
}
</script>
